﻿using MyMVC.mapper;
using MyMVC.util;
using MyUtils;
using System;
using System.Web;
using System.Web.UI;

namespace MyMVC
{
    public sealed class MVCPageHandlerFactory : IHttpHandlerFactory
    {
        private PageHandlerFactory _msPageHandlerFactory;
        private HttpContext context;

        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            this.context = context;
            // 尝试根据请求路径获取Action
            ActionMapper action = ContextLoader.getAction(url);
            if (action != null)
            {
                return action.CreateHandler(context, ContextLoader.getAutoWired());
            }
            if (url.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase))
            {
                if (_msPageHandlerFactory == null)
                    _msPageHandlerFactory = new AspnetPageHandlerFactory();
                // 调用ASP.NET默认的Page处理器工厂来处理
                return _msPageHandlerFactory.GetHandler(context, requestType, url, pathTranslated);
            }
            return new DefaultHttpHandler();
        }

        public void ReleaseHandler(IHttpHandler handler)
        {
            //清除view赋值
            if (context != null)
                context.Items.Clear();
            LogHelper.Info("ReleaseHandler");
        }
    }
}
